//
//  HMSportSpeaker.m
//  HMBest22
//
//  Created by Apple on 17/1/14.
//  Copyright © 2017年 Apple. All rights reserved.
//

#import "HMSportSpeaker.h"
#import <AVFoundation/AVFoundation.h>
#import <NSString+HMNumberConvert.h>
@interface HMSportSpeaker ()
@property (nonatomic,copy) NSString *typeString;
/// 播放语音对象
@property (nonatomic, strong) AVSpeechSynthesizer *speechSynthesizer;

/// 语音的字典
@property (nonatomic, strong) NSDictionary *voiceDict;
/// 语音播放器
@property (nonatomic, strong) AVPlayer *voicePlayer;
/// 语音数组
@property (nonatomic, strong) NSMutableArray *voiceArray;
@end
@implementation HMSportSpeaker

- (instancetype)init
{
    self = [super init];
    if (self) {
        _lastResportDistance = 0;
        _unitDistance = 0.5;
        self.speechSynthesizer = [[AVSpeechSynthesizer alloc] init];
        
        // 初始化字典 -->解析json给字典赋值
        // 1.获取路径
        NSURL *url = [[NSBundle mainBundle] URLForResource:@"voice.json" withExtension:nil subdirectory:@"voice.bundle"];
        // 2.转换成二进制文件
        NSData *data = [NSData dataWithContentsOfURL:url options:0 error:nil];
        // 3.反序列化获取字典
        self.voiceDict = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
        
        // 4.创建音乐播放对象
        self.voicePlayer = [AVPlayer new];
        
        // 5.接收播放完毕的通知
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didPlayToEndTimeNotification) name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
        
        // 在iPhone中默认只能播放一个音乐
        // 使用音乐会话的分类来开启多个音乐的播放
        // AVAudioSessionCategoryOptionMixWithOthers 允许多个音乐同时播放  音乐的音量完全一样
        // AVAudioSessionCategoryOptionDuckOthers 同时播放多个音乐 但是压低其他音量 不能再恢复其他音量
        [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback withOptions:AVAudioSessionCategoryOptionDuckOthers error:nil];
        // 激活会话
        [[AVAudioSession sharedInstance] setActive:YES error:nil];
    }
    return self;
}


/// 销毁通知
- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
// 播放运动的类型
- (void)speakVoiceWithSportType:(HMSportType)sportType
{

    switch (sportType) {
        case HMSportTypeRun:
            self.typeString = @"跑步";
            break;
        case HMSportTypeWalk:
            self.typeString = @"走路";
            break;
        case HMSportTypeBike:
            self.typeString = @"骑行";
            break;
        default:
            break;
    }
    
    NSString * typeStr= [@"开始" stringByAppendingString:self.typeString];
    [self speakString:typeStr];
}

// 播放运动的状态
- (void)speakVoiceWithSportState:(HMSportState)sportState
{
    NSString *stateString;
    switch (sportState) {
        case HMSportStatePause:
            stateString = @"放松一下吧";
            break;
        case HMSportStateContinue:
            stateString = @"运动已恢复";
            break;
        case HMSportStateFinish:
            stateString = @"运动已结束";
            break;
            
        default:
            break;
    }
    
    [self speakString:stateString];
}

// 播放运动的总距离和总时长 平均速度
- (void)speakVoiceWithDistance:(double)distance andTime:(NSTimeInterval)time andAvgSpeed:(double)avgSpeed
{
    if (distance < _lastResportDistance + _unitDistance) {
        return;
    }
    
    _lastResportDistance += _unitDistance;
    NSLog(@"播放语音了 %f",distance);
    // 距离的字符串
    NSString *distanceStr = [NSString hm_numberStringWithNumber:distance hasDotNumber:YES];
    // 时间
    NSString *timeStr = [NSString hm_timeStringWithTimeValue:time];
    // 平均速度
    NSString *speedStr = [NSString hm_numberStringWithNumber:avgSpeed hasDotNumber:YES];

    NSString *content = [NSString stringWithFormat:@"你已经 %@ %@ 公里 用时 %@ 平均速度 %@ 公里每小时 太棒了 太厉害了",self.typeString,distanceStr,timeStr,speedStr];
    NSLog(@"%@",content);
    [self speakString:content];
}

// 播放语音
// content:播放语音的内容
- (void)speakString:(NSString *)content
{
    // 根据空格截取字符串
    NSArray *array = [content componentsSeparatedByString:@" "];
    // 转换成可变数组
    self.voiceArray = [NSMutableArray arrayWithArray:array];
    
    [self playFirstVoice];
}

- (void)playFirstVoice
{
    if (self.voiceArray.count == 0) {// 语音播放完成
        [[AVAudioSession sharedInstance] setActive:NO error:nil];
        return;
    }
    // 获取数组的第一个元素
    NSString *key = self.voiceArray.firstObject;
    
    // 获取播放语音的文件名
    NSString *mp3 = self.voiceDict[key];
    // 删除数组中第一个元素
    [self.voiceArray removeObjectAtIndex:0];
    // 获取文件名对应的路径
    NSURL *url = [[NSBundle mainBundle] URLForResource:mp3 withExtension:nil subdirectory:@"voice.bundle"];
    if (url == nil) {
        NSLog(@"文件未找到  %@",key);
        // 如果文件未找到继续向下播放
        [self playFirstVoice];
        return;
    }
    // 播放条目
    AVPlayerItem *item = [AVPlayerItem playerItemWithURL:url];
    // 替换当前的条目
    [self.voicePlayer replaceCurrentItemWithPlayerItem:item];
    // 播放
    [self.voicePlayer play];

}
// 语音播放完毕后调用
- (void)didPlayToEndTimeNotification
{
    NSLog(@"一小段语音播放完毕");
    
    [self playFirstVoice];
}
@end
